package com.lab.book.web.exception;

import com.lab.cloud.common.utils.R;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)
    public R customExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        CustomException exception = (CustomException) e;
        return R.error(exception.getCode(),exception.getMessage());
    }


    @ExceptionHandler(RuntimeException.class)
    public R runtimeExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response) {
        e.printStackTrace();
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        RuntimeException exception = (RuntimeException) e;
        return R.error(400,exception.getMessage());
    }

}
